package com.heima.wemedia.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * author by itheima
 *
 * @Date 2022/3/1
 * Description
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Value("${file.oss.prefix}")
    String prefix;
    @Value("${file.oss.web-site}")
    String webSite;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //校验参数
        //文件不为空
        if (multipartFile == null || multipartFile.getSize() <= 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件参数错误");
        }
        //文件后缀
        //原始的文件名称
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!checkSuffix(suffix)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文件类型不支持");
        }
        //判断用户是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "登陆后才能上传素材");
        }
        //2.将文件上传到oss
        String newUrl = UUID.randomUUID().toString().replace(".", "") + suffix;
        try {
            newUrl = fileStorageService.store(prefix, newUrl, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "上传文件出现异常" + e.getMessage());
        }
        //3.创建Wmmaterial素材对象,存入数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(newUrl);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        this.save(wmMaterial);
        //4.相应结果  website+
        wmMaterial.setUrl(webSite + wmMaterial.getUrl());
        return ResponseResult.okResult();
    }

    //检查后缀
    private boolean checkSuffix(String suffix) {
        if (StringUtils.isBlank(suffix)) {
            return false;
        }
        List<String> list = Arrays.asList(".jpg", ".jpeg", "png", ".gif");
        for (String allowSuffix : list) {
            if (allowSuffix.equals(suffix)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 1. 素材列表查询，前台有可能给传一个条件 是否收藏  0 不收藏  1 收藏
     * 2. 只能查询当前登录用户上传的素材
     * 3. 按照发布时间 降序排序
     * 4. 返回的结果 ， 图片需要加上前缀访问路径
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //参数校验
        dto.checkParam();
        //2.执行业务查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //当前登录用户的材料
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        //时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> page = this.page(pageParam, wrapper);
        List<WmMaterial> records = page.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }
        //封装结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), records);
        return pageResponseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        //1.参数校验
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.业务处理
        //判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial vmMaterial = this.getById(id);
        if (vmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        //
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "图片有关联不能删除");
        }
        //删除素材库
        removeById(id);
        //删除图片oss
        fileStorageService.delete(vmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //收藏和取消图片
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //更新状态
        WmMaterial material = this.getById(id);
        if (material == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材信息不存在");
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if (!material.getUserId().equals(uid)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "只允许收藏自己上传的素材");
        }
        material.setIsCollection(type);
        updateById(material);
        //        update(Wrappers.<WmMaterial>lambdaUpdate()  // 如果只想修改指定字段 可以使用此方法
//                .set(WmMaterial::getIsCollection,type)
//                .eq(WmMaterial::getId,id)
//                .eq(WmMaterial::getUserId,uid));

        return ResponseResult.okResult();
    }
}
